/**********************************************************************************
Copyright (C), by AppleCai
Project                      : Study Kernel
Description                  : BSP level for MPU6500
CPU and Compiler             : AM335x,ARM-LINIX-GCC
|----------------------------------------------------------------------------------
|               R E V I S I O N   H I S T O R Y
|----------------------------------------------------------------------------------
| Date        Version  Author   Description
| --------    -------  ------   ---------------------------------------------------
| 2020-12-09  1.0.0    AppleCai MPU6500_001: Initial release version for debug acc
| 2020-12-11  1.0.1    AppleCai MPU6500_002: add all sensor and save value to txt
**********************************************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <linux/input.h>
#include <string.h>
#include <unistd.h>  
 
#define DEVICE_MPU6500			"/dev/input/event0"
  
int main(void)
{
	int fd = -1, ret = -1;
	FILE * fp;
	struct input_event ev;

	fd = open(DEVICE_MPU6500, O_RDONLY);
	if (fd < 0)
	{
		perror("open");
		return -1;
	}
	fp = fopen("test.txt", "w+");

	float val[7] = {0};
	while (1)
	{
		memset(&ev, 0, sizeof(struct input_event));
		ret = read(fd, &ev, sizeof(struct input_event));
		if (ret != sizeof(struct input_event))
		{
			perror("read");
			close(fd);
			return -1;
		}
		if(ev.type==EV_ABS)
		{
			switch(ev.code)
			{
				case ABS_X:
				    val[0] = ((short int)ev.value)/16383.0;
					printf("ACC x=%.2f ",val[0]);
					fprintf(fp, "%s %.2f ","accx=",val[0]);
					break;
				case ABS_Y:
					val[1] = ((short int)ev.value)/16383.0;
					printf("y=%.2f ",val[1]);
					fprintf(fp, "%s %.2f ","accy=",val[1]);
					break;
				case ABS_Z:
					val[2] = ((short int)ev.value)/16383.0;
					printf("z=%.2f \n",val[2]);
					fprintf(fp, "%s %.2f ","accz=",val[2]);
					break;
				case ABS_RX:
					val[3] = ((short int)ev.value)*0.001065;
					printf("Gyro x=%.2f ",val[3]);
					fprintf(fp, "%s %.2f ","gyrox=",val[3]);
					break;
				case ABS_RY:
					val[4] = ((short int)ev.value)*0.001065;
					printf("y=%.2f ",val[4]);
					fprintf(fp, "%s %.2f ","gyroy=",val[4]);
					break;
				case ABS_RZ:
					val[5] = ((short int)ev.value)*0.001065;
					printf("z=%.2f \n",val[5]);
					fprintf(fp, "%s %.2f ","gyroz=",val[5]);
					break;
				case ABS_MISC:
					//val[6] = 36.53 + (short int)ev.value/340;
					val[6] = ((short int)ev.value-21)/333.87 +21;
					printf("temp=%.2f \n",val[6]);
					break;
				default:
					break;
			}
		}
	}
	fclose(fp);
	close(fd);
	
	return 0;
}
